package settings

import (
	"time"
	"github.com/akkuman/parseConfig"
	"go-pipe/api/utilsfile"
	"github.com/globalsign/mgo"
	"go-pipe/api/utilsfile/logging"
	"database/sql"
	"github.com/jinzhu/gorm"
)

var (
	config       *parseConfig.Config
	HttpPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
	PageSize     float64
	JwtSecret    string
	MysqlUrl     string
	MongoUrl     string
	RunMode      string
	RedisUrl     string
	Password     string
	RedisMaxOpen int
	Database     int
	MaxIdleConns int

	//备用连接
	MysqlBackUrl string
	MongoBackUrl string
	RedisBackUrl string

	//时间格式化
	TimeFormat string

	//
	Mess *mgo.Session
	Db   *sql.DB
	//orm
	Dgb *gorm.DB
)

func init() {
	LoadServer()
	LoadDb()
	// LoadMongo()
	LoadMysql()
	GormFunc()
}

func LoadServer() {
	config = utilsfile.GetConfig("server", "filepath.json")
	HttpPort = int(config.Get("server > httpPort").(float64))
	RunMode = config.Get("server > runMode").(string)
	ReadTimeout = time.Duration(config.Get("server > readTimeout").(float64))
	WriteTimeout = time.Duration(config.Get("server > writeTimeout").(float64))
	TimeFormat = config.Get("format").(string)
}
func LoadDb() {

	config = utilsfile.GetConfig("db", "filepath.json")

	MysqlUrl = config.Get("mysql > host").(string)
	MysqlBackUrl = config.Get("mysql > backhost").(string)
	MongoUrl = config.Get("mongo > host").(string)
	MongoBackUrl = config.Get("mongo > backhost").(string)
	RedisUrl = config.Get("redis > host").(string)
	RedisBackUrl = config.Get("redis > backhost").(string)
	Password = config.Get("redis > password").(string)
	Database = int(config.Get("redis > database").(float64))
	RedisMaxOpen = int(config.Get("redis > maxOpen").(float64))
	MaxIdleConns = int(config.Get("redis > maxIdle").(float64))

}

func LoadMongo() {
	var err error
	Mess, err = mgo.Dial(MongoUrl)
	if nil != err {
		logging.Error("Mongo", "500", time.Now().Format(TimeFormat), err.Error())
		Mess.Close()
	}
}

func LoadMysql() {
	Db, _ = sql.Open("mysql", MysqlUrl)
	Db.SetMaxOpenConns(2000)
	Db.SetMaxIdleConns(1000)
	Db.Ping()
	//CheckErr(err)

}

func GormFunc() {
	var err error
	Dgb, err = gorm.Open("mysql", MysqlUrl)
	if err != nil {
		logging.Error("gorm", "400", time.Now().Format(TimeFormat), err.Error())
		Dgb.Close()
	}
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return "blog_" + defaultTableName;
	}
	Dgb.SingularTable(true)
}
